//
//  CardDataService.swift
//  memo
//
//  Created by DaleGuo on 2023/10/1.
//

import CoreData
import Foundation
import WidgetKit

class MemoDataService {
    static let memoDataService = MemoDataService()
    var viewContext = PersistenceController.shared.viewContext
    private let containerName = "memo"

    private let memoName = "MemoEntity"

    @Published var allMemos: [MemoEntity] = []
    
    init() {
        getAllMemos()
    }
    
    func getAllMemos() {
        let request = NSFetchRequest<MemoEntity>(entityName: memoName)
        request.sortDescriptors = [NSSortDescriptor(keyPath: \MemoEntity.updated_date_, ascending: false), NSSortDescriptor(keyPath: \MemoEntity.title_, ascending: true)]

        do {
            allMemos = try viewContext.fetch(request)
//            print("下面是service中的数据：")
//            allMemos.forEach { MemoEntity in
//                MemoEntity.todos.forEach { TodoEntity in
//                    print(TodoEntity.content + "  -  "+TodoEntity.is_completed.description)
//                }
//            }
            
        } catch {
            print("Error fetching portfolio entity: \(error)")
        }
    }
    
  
    
    // memo的title可以为空
    func addMemo(title: String = "", content: String) -> MemoEntity {
//        print(viewContext)
        let memoEntity = MemoEntity(context: viewContext)
        
        memoEntity.title = title
        memoEntity.content = content
        memoEntity.updated_date = Date()
        
        save()
        
        return memoEntity

//        getAllMemos()
    }
    
    func delete(entity: MemoEntity) {
        viewContext.delete(entity)
        save()
        getAllMemos()
    }
    
    func deleteMemos(memos: [MemoEntity]) {
        memos.forEach { viewContext.delete($0) }
        save()
        getAllMemos()
    }
    
    func rollbackMemos(memos:[MemoEntity]) {
        memos.forEach {  $0.del_flag.toggle() }
        save()
        getAllMemos()
    }
    
    func deleteTodo(todo: TodoEntity) {
        // 找到这个 todo
        viewContext.delete(todo)
        
        save()
//        getAllMemos()
    }
    
    func save() {
        do {
            try viewContext.save()
            WidgetCenter.shared.reloadTimelines(ofKind: "memoWidget")
        } catch {
            print("Error saving data! \(error)")
        }
    }
    
    private let todoName = "TodoEntity"
    
    //
    func updateTodo(todo: TodoEntity, content: String, is_completed: Bool, level: Bool) {
        todo.is_completed = is_completed
        todo.content = content
        todo.level = level
        save()
        print("UPdate")
        // 需要重新获取所有Memo，因为 view中绑定的是memos
//        MemoDataService.memoDataService_preview.getAllMemos()
        
        getAllMemos()
    }
    
    
    func addTodo(content: String, memo: MemoEntity) {
        let todo = TodoEntity(context: viewContext)
        todo.content = content
        todo.updated_date = Date()
        todo.memo = memo
        
        save()
        getAllMemos()
    }
    
    func toggle_memo_del(memo: MemoEntity) {
        memo.del_flag.toggle()
        save()
        getAllMemos()
    }
    
//
//    static var todo_preview: TodoEntity {
//        let context = memoDataService_preview.container.viewContext
//        let todo = TodoEntity(context: context)
//        todo.content = "这是一个测试todo"
//        todo.is_completed = false
//
//        return todo
//    }
}
